import * as echarts from "echarts";
import { ElMessageBox } from 'element-plus'
import store from '@/store'

const fcolor = '#b9b8ce' //公共样式
var myChart = null //图表对象
var option = null //图标配置
var dataZoom = {
    "start": 86.66666666666667,
    "end": 100,
} //图表缩放配置
export let OCLH = {}
export let MACDA = {}
var onClick = false //触发点击
var tagToolboxs = [] //要展示的文字/线段 自定义toolbox
var setTypeToolbox = null //点击事件里判断触发的自定义toolbox 标文字 1/线段 2

var maiMaiIcon = 'path://M52.8,50.2l0-4l2,0l0,4L52.8,50.2z M52.7,44.7l-0.1-10l2,0l0.1,10L52.7,44.7z M52.6,33.2l-0.1-10l2,0l0.1,10L52.6,33.2z M52.5,21.7l-0.1-10l2,0l0.1,10L52.5,21.7z M52.4,10.2l-0.1-10l2,0l0.1,10L52.4,10.2z'
// 处理k线
async function dlKlinesOption(rawData) {
    const categoryData = [];
    const values = [];
    rawData.map(i => {
        // x轴名称
        categoryData.push(i.date);
        // 值
        let value = Object.values(i)
        values.push([
            i.o,
            i.c,
            i.l,
            i.h
        ]);
    })

    let color = await getColor()
    return {
        series: {
            name: 'Kline',
            type: "candlestick",
            xAxisIndex: 0,
            yAxisIndex: 0,
            data: values,
            barWidth: '50%',
            large: false,
            z: 1,
            disabled: false,
            tooltip: {
                show: true,
                formatter: (params) => {
                    // 自定义label OCLH
                    const { seriesName, dataIndex } = params
                    OCLH = rawData[dataIndex]
                }
            },
            itemStyle: {
                color: color[0],
                color0: color[1],
                borderColor: color[0],
                borderColor0: color[1]
            }
        },
        xAxis: {
            type: "category",
            gridIndex: 0,
            boundaryGap: false,
            axisLine: {
                onZero: false,
                lineStyle: {
                    color: '#000'
                }
            },
            axisLabel: { show: false },
            axisTick: { show: false },
            splitLine: { show: false },
            min: 'dataMin',
            max: 'dataMax',
            data: categoryData
        },
        yAxis: {
            show: true,
            scale: true,
            nameGap: 15,
            gridIndex: 0,
            position: 'right',
            axisLine: {
                show: false,
                onZero: true,
                onZeroAxisIndex: 0,
                lineStyle: {
                    color: fcolor,
                }
            },
            axisTick: {
                show: false,
                alignWithLabel: false,
                inside: false
            },
            axisLabel: {
                show: true,
                position: "top",
                margin: 8,
            },
            inverse: false,
            offset: 0,
            splitNumber: 5,
            minInterval: 0,
            splitLine: {
                show: false
            }
        }
    }
}
// 处理顶点
async function dlPointDingOption(rawData) {
    const data = await dlBaseFn(rawData)
    return {
        series: {
            type: "scatter",
            name: "顶",
            data: data.values,
            xAxisIndex: 0,
            yAxisIndex: 0,
            symbolSize: 2,
            legendHoverLink: false,
            label: {
                show: false,
                position: "top",
                margin: 8
            },
            itemStyle: {
                color: "red"
            },
            large: true,
            largeThreshold: 0,
            animation: false
        },
    }
}
// 底
async function dlPointDiOption(rawData) {
    const data = await dlBaseFn(rawData)
    return {
        series: {
            type: "scatter",
            name: "底",
            data: data.values,
            xAxisIndex: 0,
            yAxisIndex: 0,
            symbolSize: 2,
            legendHoverLink: false,
            label: {
                show: false,
                position: "top",
                margin: 8
            },
            itemStyle: {
                color: "green"
            },
            large: true,
            largeThreshold: 0,
            animation: false
        },
    }
}
//笔
async function dlLineBisOption(rawData) {
    const data = await dlBaseFn(rawData)
    return {
        series: {
            type: "line",
            name: "笔",
            data: data.values,
            connectNulls: false,
            xAxisIndex: 0,
            yAxisIndex: 0,
            symbolSize: 4,
            showSymbol: true,
            smooth: false,
            sampling: 'average',//降采样策略
            step: false,
            emphasis: {
                disabled: true
            },
            animation: false,
            "hoverAnimation": false,
            label: {
                show: false,
                position: "top",
                margin: 8
            },
            lineStyle: {
                show: true,
                width: 1,
                opacity: 1,
                curveness: 0,
                color: "#fddd60"
            },
            areaStyle: {
                opacity: 0
            },
            zlevel: 0,
            z: 0
        },
    }
}
// 线
async function dlLineXdsOption(rawData) {
    const data = await dlBaseFn(rawData)
    return {
        series: {
            type: "line",
            name: "线段中枢",
            data: data.values,
            connectNulls: false,
            xAxisIndex: 0,
            yAxisIndex: 0,
            symbolSize: 4,
            showSymbol: true,
            smooth: false,
            sampling: 'average',//降采样策略
            step: false,
            emphasis: {
                disabled: true
            },
            animation: false,
            "hoverAnimation": false,
            lineStyle: {
                show: true,
                width: 1,
                opacity: 1,
                curveness: 0,
                color: "#FF9966"
            },
            areaStyle: {
                opacity: 0
            },
            zlevel: 0
        },
    }
}
// 线段中枢
function dlLineXdszssOption(rawData) {
    let series = []
    let baseOps = {
        "type": "line",
        "name": "线段中枢",
        "connectNulls": false,
        "xAxisIndex": 0,
        "yAxisIndex": 0,
        "symbolSize": 0,
        "showSymbol": true,
        "smooth": false,
        "clip": true,
        "step": false,
        sampling: 'average',//降采样策略
        emphasis: {
            disabled: true
        },
        animation: false,
        "hoverAnimation": false,
        "areaStyle": {
            "opacity": 0
        },
        "zlevel": 0,
        "z": 0
    }
    // 类型一    
    rawData.map(async i => {
        const { start_index, low_val, high_val, end_index, type, style, weight } = i
        let color = await getColor({ type, style })
        let lineStyle = {
            "show": true,
            "width": 1,
            "opacity": 1,
            "curveness": 0,
            "type": "solid",
            color
        }
        let areaStyle = {
            color,
            opacity: .5,
            origin: low_val
        }
        let label = {
            "show": true,
            "position": "insideBottomLeft",
            "margin": 8,
            color,
            formatter: function (params) {
                let a = i.label.split('(')[0]
                let b = '(' + i.label.split('(')[1]
                try {
                    a = i.label.split('(')[0]
                    b = '(' + i.label.split('(')[1]
                } catch (error) {
                    a = i.label
                    error;
                }
                return `{a|${a}} {b|${b}}`;
            },
            rich: {
                a: {
                    fontSize: 18,
                },
                b: {
                    fontSize: 12,
                }
            }
        }
        series.push(
            // 提示
            {
                ...baseOps,
                label,
                tooltip: {
                    show: false,
                },
                "data": [
                    [start_index, high_val]
                ],
            },
            // 上
            {
                ...baseOps,
                lineStyle,
                "data": [
                    [start_index, low_val], [start_index, high_val]
                ],
            },
            // 右
            {
                ...baseOps,
                lineStyle,
                areaStyle,
                tooltip: {
                    show: false,
                },
                "data": [
                    [start_index, high_val], [end_index, high_val]
                ],
            },
            // 下
            {
                ...baseOps,
                lineStyle,
                "data": [
                    [end_index, high_val], [end_index, low_val]
                ],
            },
            // 左
            {
                ...baseOps,
                lineStyle,
                tooltip: {
                    show: false,
                },
                "data": [
                    [start_index, low_val], [end_index, low_val]
                ],
            }
        )
    })

    return {
        series
    }
}
// 线段走势
async function dlLineQsOption(rawData) {
    const data = await dlBaseFn(rawData)
    return {
        series: {
            type: "line",
            name: "走势",
            data: data.values,
            connectNulls: false,
            xAxisIndex: 0,
            yAxisIndex: 0,
            symbolSize: 0,
            showSymbol: true,
            smooth: false,
            sampling: 'average',//降采样策略
            step: false,
            emphasis: {
                disabled: true
            },
            animation: false,
            "hoverAnimation": false,
            lineStyle: {
                show: true,
                width: 1,
                opacity: 1,
                curveness: 0
            },
            areaStyle: {
                opacity: 0
            },
            zlevel: 0
        },
    }
}
// 线段卖点
function dlLineXdSellOption(rawData) {
    const data = rawData
    const result = []
    const baseSeries = {
        "type": "scatter",
        "name": "线段卖点",
        "xAxisIndex": 0,
        "yAxisIndex": 0,
        "symbol": maiMaiIcon,
        "symbolSize": [2, 25],
        "symbolRotate": 180,
        "tooltip": {
            "show": true,
            "trigger": "item",
            "triggerOn": "mousemove|click",
            "axisPointer": {
                "type": "line"
            },
            "showContent": true,
            "alwaysShowContent": false,
            "showDelay": 0,
            "hideDelay": 100,
            "formatter": function (params) { return params.value[2] + params.value[1]; },
            "textStyle": {
                "fontSize": 18
            },
            "borderWidth": 0,
            "padding": 5
        },
        legendHoverLink: false,
        animation: false
    }
    const label = {
        "show": true,
        "position": "top",
        "margin": 8,
    }
    data.map(async i => {
        let color = await getColor({ style: i.style })
        result.push({
            ...baseSeries,
            color,
            label: {
                ...label,
                color,
                formatter: getLabel(i.type)
            },
            data: [[
                i.index,
                i.val[0] || null,
                i.val[1] || null,
            ]],
            itemStyle: {
                color
            }
        }
        )
    })


    return {
        series: result,
    }
}
// 线段买点
function dlLinexdBuyOption(rawData) {
    const data = rawData
    const result = []
    const baseSeries = {
        "type": "scatter",
        "name": "线段买点",
        "xAxisIndex": 0,
        "yAxisIndex": 0,
        "symbol": maiMaiIcon,
        "symbolSize": [2, 25],
        "tooltip": {
            "show": true,
            "trigger": "item",
            "triggerOn": "mousemove|click",
            "axisPointer": {
                "type": "line"
            },
            "showContent": true,
            "alwaysShowContent": false,
            "showDelay": 0,
            "hideDelay": 100,
            "formatter": function (params) { return params.value[2] + params.value[1]; },
            "textStyle": {
                "fontSize": 18
            },
            "borderWidth": 0,
            "padding": 5
        },
        legendHoverLink: false,
        animation: false
    }
    const label = {
        "show": true,
        "position": "bottom",
        "margin": 8
    }
    data.map(async i => {
        let color = await getColor({ style: i.style })
        result.push({
            ...baseSeries,
            color,
            label: {
                ...label,
                color,
                formatter: getLabel(i.type)
            },
            data: [[
                i.index,
                i.val[0] || null,
                i.val[1] || null,
            ]],
            itemStyle: {
                color
            }
        }
        )
    })
    return {
        series: result
    }
}
// boll
async function dlBollOption(rawData) {
    const baseSeries = {
        "type": "line",
        "name": "BOLL",
        "connectNulls": false,
        "xAxisIndex": 1,
        "yAxisIndex": 1,
        "symbolSize": 4,
        "showSymbol": false,
        "smooth": false,
        "step": false,
        sampling: 'average',//降采样策略
        emphasis: {
            disabled: true
        },
        animation: false,
        "hoverAnimation": false,
        "label": {
            "show": false,
            "position": "top",
            "margin": 8
        },
        "lineStyle": {
            "show": true,
            "width": 1,
            "opacity": 1,
            "curveness": 0,
            "type": "solid",
            "color": "#99CC99"
        },
        "areaStyle": {
            "opacity": 0
        },
        "zlevel": 0
    }
    const low = []
    const mid = []
    const up = []
    rawData.map(i => {
        low.push(i.low)
        mid.push(i.mid)
        up.push(i.up)
    })
    return {
        series: [{
            ...baseSeries,
            data: mid,
        },
        {
            ...baseSeries,
            data: low
        },
        {
            ...baseSeries,
            data: up,
        }]
    }
}
// macd
async function dlMacdOption(rawData) {
    const { MACD, klines } = rawData
    // MACD
    const MACDSeries = {
        "type": "line",
        "name": "MACD",
        "connectNulls": false,
        "xAxisIndex": 2,
        "yAxisIndex": 2,
        "symbolSize": 0,
        "showSymbol": false,
        "smooth": false,
        "clip": true,
        "step": false,
        sampling: 'average',//降采样策略
        emphasis: {
            disabled: true
        },
        animation: false,
        "hoverAnimation": false,
        "label": {
            "show": false,
            "position": "top",
            "margin": 8
        },
        "areaStyle": {
            "opacity": 0
        },
        "zlevel": 0,
        tooltip: {
            show: true,
            formatter: (params) => {
                // 自定义label MACDA
                const { seriesName, dataIndex } = params
                MACDA = MACD[dataIndex]
            }
        }
    }
    const lineStyle = {
        "show": true,
        "width": 1,
        "opacity": 1,
        "curveness": 0,
        "type": "solid"
    }
    const hist = []
    const dif = []
    const dea = []
    MACD.map(i => {
        hist.push(i.hist)
        dif.push(i.dif)
        dea.push(i.dea)
    })
    // Klines_a
    const Klines_aSeries = {
        name: 'Klines_a',
        type: "bar",
        itemStyle: {
            color: '#e82f7b'
        },
        xAxisIndex: 2,
        yAxisIndex: 2
    }
    const date = []
    const a = []
    klines.map(i => {
        date.push(i.date)
        a.push(i.a)
    })
    return {
        xAxis: {
            name: 'MACD',
            type: "category",
            show: true,
            gridIndex: 2,
            data: date,
            boundaryGap: false,
            axisLine: {
                onZero: false,
                lineStyle: {
                    color: fcolor,
                }
            },
            splitLine: { show: false },
        },
        yAxis: {
            show: true,
            scale: true,
            nameGap: 15,
            gridIndex: 2,
            position: 'right',
            axisLine: {
                show: false,
                onZero: true,
                onZeroAxisIndex: 0,
                lineStyle: {
                    color: fcolor,
                }
            },
            axisTick: {
                show: false,
                alignWithLabel: false,
                inside: false
            },
            axisLabel: {
                show: true,
                position: "top",
                margin: 8,
            },
            inverse: false,
            offset: 0,
            splitNumber: 5,
            minInterval: 0,
            splitLine: {
                show: false
            }
        },
        series: [{
            ...MACDSeries,
            lineStyle: {
                ...lineStyle,
                color: '#fff'
            },
            data: dif,
        },
        {

            ...MACDSeries,
            type: "bar",
            itemStyle: {
                color: "#fd1050"
            },
            data: hist.map(i => {
                if (i > 0) return i;
            })
        },
        {

            ...MACDSeries,
            type: "bar",
            itemStyle: {
                color: "#0cf49b"
            },
            data: hist.map(i => {
                if (i < 0) return i;
            })
        },
        {
            ...MACDSeries,
            data: dea,
            lineStyle: {
                ...lineStyle,
                color: '#F7BA0B'
            },
        }, {
            ...Klines_aSeries,
            data: a
        }]
    }
}
// 笔中枢
function dlLineBiZssOption(rawData) {
    const { type1, type2, type3 } = rawData
    let series = []
    let baseOps = {
        "type": "line",
        "name": "笔中枢",
        "connectNulls": false,
        "xAxisIndex": 0,
        "yAxisIndex": 0,
        "symbolSize": 0,
        "showSymbol": true,
        "smooth": false,
        "clip": true,
        "step": false,
        sampling: 'average',//降采样策略
        emphasis: {
            disabled: true
        },
        animation: false,
        "hoverAnimation": false,
        "areaStyle": {
            "opacity": 0
        },
        "zlevel": 0,
        "z": 0
    }
    // 类型一    
    type1.map(async i => {
        const { start_index, low_val, high_val, end_index, type, style, weight } = i
        let color = await getColor({ type, style })
        let lineStyle = {
            "show": true,
            "width": 1,
            "opacity": 1,
            "curveness": 0,
            "type": "solid",
            color
        }
        let areaStyle = {
            color,
            opacity: .5,
            origin: low_val
        }
        let label = {
            "show": true,
            "position": "insideBottomLeft",
            "margin": 8,
            color,
            formatter: function (params) {
                if (!i.label) return ''
                let a = i.label.split('(')[0]
                let b = '(' + i.label.split('(')[1]
                try {
                    a = i.label.split('(')[0]
                    b = '(' + i.label.split('(')[1]
                } catch (error) {
                    a = i.label
                    error;
                }
                return `{a|${a}} {b|${b}}`;
            },
            rich: {
                a: {
                    fontSize: 18,
                },
                b: {
                    fontSize: 12,
                }
            }
        }
        series.push(
            // 提示
            {
                ...baseOps,
                label,
                tooltip: {
                    show: false,
                },
                "data": [
                    [start_index, high_val]
                ],
            },
            // 上
            {
                ...baseOps,
                lineStyle,
                "data": [
                    [start_index, low_val], [start_index, high_val]
                ],
            },
            // 右
            {
                ...baseOps,
                lineStyle,
                areaStyle,
                tooltip: {
                    show: false,
                },
                "data": [
                    [start_index, high_val], [end_index, high_val]
                ],
            },
            // 下
            {
                ...baseOps,
                lineStyle,
                "data": [
                    [end_index, high_val], [end_index, low_val]
                ],
            },
            // 左
            {
                ...baseOps,
                lineStyle,
                tooltip: {
                    show: false,
                },
                "data": [
                    [start_index, low_val], [end_index, low_val]
                ],
            }
        )
    })
    // 类型二
    type2.map(async i => {
        const { start_index, low_val, high_val, end_index, type, style, weight } = i
        let color = await getColor({ type, style })

        let lineStyle = {
            "show": true,
            "width": 1,
            "opacity": 1,
            "curveness": 0,
            "type": "dashed",
            color
        }
        let label = {
            "show": true,
            "position": "insideBottomLeft",
            "margin": 8,
            color,
            formatter: function (params) {
                let a = i.label.split('(')[0]
                let b = '(' + i.label.split('(')[1]
                try {
                    a = i.label.split('(')[0]
                    b = '(' + i.label.split('(')[1]
                } catch (error) {
                    a = i.label
                    error;
                }
                return `{a|${a}} {b|${b}}`;
            },
            rich: {
                a: {
                    fontSize: 18,
                },
                b: {
                    fontSize: 12,
                }
            }
        }
        series.push(
            // 提示
            {
                ...baseOps,
                label,
                tooltip: {
                    show: false,
                },
                "data": [
                    [start_index, high_val]
                ],
            },
            // 上
            {
                ...baseOps,
                lineStyle,
                "data": [
                    [start_index, low_val], [start_index, high_val]
                ]
            },
            // 右
            {
                ...baseOps,
                lineStyle,
                tooltip: {
                    show: false,
                },
                "data": [
                    [start_index, high_val], [end_index, high_val]
                ],
            },
            // 下
            {
                ...baseOps,
                lineStyle,
                "data": [
                    [end_index, high_val], [end_index, low_val]
                ],
            },
            // 左
            {
                ...baseOps,
                lineStyle,
                tooltip: {
                    show: false,
                },
                "data": [
                    [start_index, low_val], [end_index, low_val]
                ],
            }
        )
    })
    // 类型三
    type3.map(async i => {
        const { start_index, low_val, high_val, end_index, type, style, weight } = i
        let color = await getColor({ type, style })

        let lineStyle = {
            "show": true,
            "width": 1,
            "opacity": 1,
            "curveness": 0,
            "type": "dashed",
            color
        }
        let label = {
            "show": true,
            "position": "insideBottomLeft",
            "margin": 8,
            color,
            fontSize: 18,
            formatter: function (params) {
                return i.label;
            },
        }
        series.push(
            // 提示
            {
                ...baseOps,
                label,
                tooltip: {
                    show: false,
                },
                "data": [
                    [start_index, high_val]
                ],
            },
            // 上
            {
                ...baseOps,
                lineStyle,
                "data": [
                    [start_index, low_val], [start_index, high_val]
                ],
            },
            // 右
            {
                ...baseOps,
                lineStyle,
                tooltip: {
                    show: false,
                },
                "data": [
                    [start_index, high_val], [end_index, high_val]
                ],
            },
            // 下
            {
                ...baseOps,
                lineStyle,
                "data": [
                    [end_index, high_val], [end_index, low_val]
                ],
            },
            // 左
            {
                ...baseOps,
                lineStyle,
                tooltip: {
                    show: false,
                },
                "data": [
                    [start_index, low_val], [end_index, low_val]
                ],
            }
        )
    })

    return {
        series
    }
}
// 笔背驰
function dlPointBiBcsOption(rawData) {
    const data = rawData
    const result = []
    data.map(i => {
        result.push([
            i.index,
            i.val[0] || null,
            i.val[1] || null,
        ])
    })
    return {
        series: {
            "type": "scatter",
            "name": "笔背驰",
            "xAxisIndex": 0,
            "yAxisIndex": 0,
            "symbol": "circle",
            "symbolSize": 10,
            "data": result,
            "label": {
                "show": false,
                "position": "top",
                "margin": 8
            },
            "tooltip": {
                "show": true,
                "trigger": "item",
                "triggerOn": "mousemove|click",
                "axisPointer": {
                    "type": "line"
                },
                "showContent": true,
                "alwaysShowContent": false,
                "showDelay": 0,
                "hideDelay": 100,
                "formatter": function (params) { return params.value[2]; },
                "textStyle": {
                    "fontSize": 18
                },
                "borderWidth": 0,
                "padding": 5
            },
            "itemStyle": {
                "color": "rgba(223,148,100,0.7)"
            },
            large: true
        },
    }
}
// 卖点
function dlScatterSellOption(rawData) {
    const data = rawData
    const result = []
    const baseSeries = {
        "type": "scatter",
        "name": "笔卖点",
        "xAxisIndex": 0,
        "yAxisIndex": 0,
        "symbol": maiMaiIcon,
        "symbolSize": [2, 25],
        "symbolRotate": 180,
        "tooltip": {
            "show": true,
            "trigger": "item",
            "triggerOn": "mousemove|click",
            "axisPointer": {
                "type": "line"
            },
            "showContent": true,
            "alwaysShowContent": false,
            "showDelay": 0,
            "hideDelay": 100,
            "formatter": function (params) { return params.value[2] + params.value[1]; },
            "textStyle": {
                "fontSize": 18
            },
            "borderWidth": 0,
            "padding": 5
        },
        legendHoverLink: false,
        animation: false
    }
    const label = {
        "show": true,
        "position": "top",
        "margin": 8,
    }
    data.map(async i => {
        let color = await getColor({ style: i.style })
        result.push({
            ...baseSeries,
            color,
            label: {
                ...label,
                color,
                formatter: getLabel(i.type)
            },
            data: [[
                i.index,
                i.val[0] || null,
                i.val[1] || null,
            ]],
            itemStyle: {
                color
            }
        }
        )
    })


    return {
        series: result,
    }
}
// 买点
function dlScatterBuyOption(rawData) {
    const data = rawData
    const result = []
    const baseSeries = {
        "type": "scatter",
        "name": "笔买点",
        "xAxisIndex": 0,
        "yAxisIndex": 0,
        "symbol": maiMaiIcon,
        "symbolSize": [2, 25],
        "tooltip": {
            "show": true,
            "trigger": "item",
            "triggerOn": "mousemove|click",
            "axisPointer": {
                "type": "line"
            },
            "showContent": true,
            "alwaysShowContent": false,
            "showDelay": 0,
            "hideDelay": 100,
            "formatter": function (params) { return params.value[2] + params.value[1]; },
            "textStyle": {
                "fontSize": 18
            },
            "borderWidth": 0,
            "padding": 5
        },
        legendHoverLink: false,
        animation: false
    }
    const label = {
        "show": true,
        "position": "bottom",
        "margin": 8
    }
    data.map(async i => {
        let color = await getColor({ style: i.style })
        result.push({
            ...baseSeries,
            color,
            label: {
                ...label,
                color,
                formatter: getLabel(i.type)
            },
            data: [[
                i.index,
                i.val[0] || null,
                i.val[1] || null,
            ]],
            itemStyle: {
                color
            }
        }
        )
    })
    return {
        series: result
    }
}
// 海底捞月
function dlSeaMoonOption(rawData) {
    const baseSeries = {
        "type": "line",
        "connectNulls": false,
        "xAxisIndex": 1,
        "yAxisIndex": 1,
        "symbolSize": 0,
        "showSymbol": false,
        "smooth": false,
        "clip": true,
        "step": false,
        sampling: 'average',//降采样策略
        emphasis: {
            disabled: true
        },
        animation: false,
        "hoverAnimation": false,
        "areaStyle": {
            "opacity": 0
        },
        "zlevel": 0
    }
    const lineStyle = {
        show: true,
        width: 1,
        opacity: 1,
        curveness: 0,
        color: '#ff1e10',
        type: "solid"
    }

    const date = []
    const vol = []
    const risk = []
    const updown = []

    rawData.map(i => {
        date.push(i.date)
        vol.push(i.vol)
        risk.push(i.risk)
        updown.push(i.updown)
    })
    return {
        xAxis: {
            type: "category",
            show: true,
            gridIndex: 1,
            boundaryGap: false,
            data: date,
            axisLine: {
                onZero: false,
                lineStyle: {
                    color: '#000'
                }
            },
            axisLabel: { show: false },
            axisTick: { show: false },
            splitLine: { show: false },
        },
        yAxis: {
            show: true,
            scale: true,
            nameGap: 15,
            gridIndex: 1,
            position: 'right',
            axisLine: {
                show: false,
                onZero: true,
                onZeroAxisIndex: 0,
                lineStyle: {
                    color: fcolor,
                }
            },
            axisTick: {
                show: false,
                alignWithLabel: false,
                inside: false
            },
            axisLabel: {
                show: true,
                position: "top",
                margin: 8,
            },
            inverse: false,
            offset: 0,
            splitNumber: 5,
            minInterval: 0,
            splitLine: {
                show: false
            }
        },
        series: [
            {
                ...baseSeries,
                data: vol,
                name: 'VOL',
                type: "bar",
                itemStyle: {
                    color: '#e82f7b'
                }
            },
            {

                ...baseSeries,
                "data": risk,
                name: 'RISk',
                lineStyle: {
                    ...lineStyle,
                    color: '#1aad19',
                    type: "solid"
                }
            },
            {
                ...baseSeries,
                "data": updown,
                name: 'UPDOWN',
                lineStyle: {
                    ...lineStyle
                }
            }]
    }
}
// 均值
async function dlMainAreaOption(rawData) {
    const ma_fast = rawData.map(i => [i.date, i.ma_fast])
    const ma_slow = rawData.map(i => [i.date, i.ma_slow])
    const baseSeries = {
        type: "line",
        name: "主力三区",
        connectNulls: false,
        xAxisIndex: 0,
        yAxisIndex: 0,
        symbolSize: 0,
        showSymbol: true,
        smooth: false,
        clip: true,
        step: false,
        sampling: 'average',//降采样策略
        emphasis: {
            disabled: true
        },
        animation: false,
        hoverAnimation: false,
        zlevel: 0
    }
    const lineStyle = {
        show: true,
        width: 1,
        opacity: 1,
        curveness: 0
    }
    return {
        series: [{
            ...baseSeries,
            data: ma_fast,
            lineStyle: {
                ...lineStyle,
                color: '#1699ff'
            }
        }, {
            ...baseSeries,
            data: ma_slow,
            lineStyle: {
                ...lineStyle,
                color: '#ffbe00'
            }
        }]
    }
}
// 公共方法 处理顶点 处理底点 处理笔
function dlBaseFn(rawData) {
    const values = [];
    rawData.map(i => {
        let value = Object.values(i)
        values.push(value);
    })
    return {
        values
    }
}
// 公共方法 获取颜色 处理买卖点 笔中枢
function getColor(data) {
    let color = null
    let TYPE = store.getters.system.type //港股/美股
    let colorArr = [
        '#fd1050', //红
        '#0cf49b', //绿
        '#D9D919', //黄
        '#9932CD', //紫
        '#ff3d3f',//亮红
        '#82ff3d'//亮绿
    ]
    if (!data && TYPE == 1) return [colorArr[0], colorArr[1]];
    if (!data && TYPE == 2) return [colorArr[1], colorArr[0]];

    const { type = '', style = '' } = data
    //美股
    if (TYPE == 2) {
        if (type == 'up') color = colorArr[1];
        else color = colorArr[0];
        if (Number(style) == 1) color = colorArr[0];
        if (Number(style) == 2) color = colorArr[4];
        if (Number(style) == 3) color = colorArr[1];
        if (Number(style) == 6) color = colorArr[5];
        if (Number(style) == 9) color = colorArr[2];
        if (Number(style) > 9) color = colorArr[3]
        return color
    }
    // 港股
    if (type == 'up') color = colorArr[0];
    else color = colorArr[1];
    if (Number(style) == 1) color = colorArr[0];
    if (Number(style) == 9) color = colorArr[2];
    if (Number(style) > 9) color = colorArr[3]
    return color
}
// 公共方法 获取买卖值 处理买卖点
function getLabel(e) {
    let str = String(e)
    const a = str.slice(0, 1)
    let b = ''
    if (a == '1' && str.indexOf('buy') > 0) {
        b = '①买'
    }
    if (a == '2' && str.indexOf('buy') > 0) {
        b = '②买'
    }
    if (a == '3' && str.indexOf('buy') > 0) {
        b = '③买'
    }
    if (a == '1' && str.indexOf('sell') > 0) {
        b = '①卖'
    }
    if (a == '2' && str.indexOf('sell') > 0) {
        b = '②卖'
    }
    if (a == '3' && str.indexOf('sell') > 0) {
        b = '③卖'
    }
    return b
}
export const creatKline = async (dom, data) => {
    // 刷新
    onClick = false //触发点击
    setTypeToolbox = null //点击事件里判断触发的自定义toolbox 标文字 1/线段 2

    // console.log(data)
    const {
        title = '',//标题
        klines = [],//k线 o开盘 c收盘 l低 h高 a成交量
        idx = {},//指标，包括boll , macd
        // point_ding = [],//顶点 index 时间 ， val价格，下同
        // point_di = [],//底点
        line_bis = [],//笔
        line_xds = [],//线段中枢
        line_xd_zss = [],//线段中枢
        xd_buy = [],//线段买点
        xd_sell = [],//线段卖点
        line_qs = [], //走势线
        line_bi_zss = [],//笔中枢
        line_bi_zss_ex2 = [],//笔中枢
        line_bi_zss_ex3 = [],//笔中枢
        point_bi_bcs = [],//笔背驰
        scatter_buy = [],//买点
        scatter_sell = [],//卖点
        sea_moon = [], //海底捞月
        main_area = [] //均值
    } = data

    const klinesOption = await dlKlinesOption(klines)
    // const pointDingOption = await dlPointDingOption(point_ding)
    // const pointDiOption = await dlPointDiOption(point_di)
    const lineBisOption = await dlLineBisOption(line_bis)
    const lineXdsOption = await dlLineXdsOption(line_xds)
    const lineXdszssOption = await dlLineXdszssOption(line_xd_zss)
    const linexdBuyOption = await dlLinexdBuyOption(xd_buy)
    const lineXdSellOption = await dlLineXdSellOption(xd_sell)

    const lineQsOption = await dlLineQsOption(line_qs)

    // const bollOption = await dlBollOption(idx.boll)
    const macdOption = await dlMacdOption({
        MACD: idx.macd,
        klines
    })
    const lineBiZssOption = await dlLineBiZssOption({
        type1: line_bi_zss,
        type2: line_bi_zss_ex2,
        type3: line_bi_zss_ex3,
    })
    const pointBiBcsOption = await dlPointBiBcsOption(point_bi_bcs)
    const scatterBuyOption = await dlScatterBuyOption(scatter_buy)
    const scatterSellOption = await dlScatterSellOption(scatter_sell)
    const seaMoonOption = await dlSeaMoonOption(sea_moon)
    const mainAreaOption = await dlMainAreaOption(main_area)


    myChart = echarts.init(dom)
    myChart.off('click')

    // 响应式
    const screenWidth = store.getters.system.screenWidth
    //设置参数
    option = {
        color: [
            "#fddd60",
            "#ffa710",
            "#da6ee8",
            "#a1bffc",
            "#cccccc",
            "#ffe8a7",
            "#da6ee8",
            "#6e7074",
            "#546570",
            "#c4ccd3",
            "#f05b72",
            "#ef5b9c",
            "#f47920",
            "#905a3d",
            "#fab27b",
            "#2a5caa",
            "#444693",
            "#726930",
            "#b2d235",
            "#6d8346",
            "#ac6767",
            "#1d953f",
            "#6950a1",
            "#918597"
        ],
        series: [
            klinesOption.series,
            // pointDingOption.series,
            // pointDiOption.series,
            lineBisOption.series,
            lineXdsOption.series,
            ...lineXdszssOption.series,
            lineQsOption.series,
            ...linexdBuyOption.series,
            ...lineXdSellOption.series,
            // ...bollOption.series,
            ...macdOption.series.filter(i => i.name == 'MACD'),
            ...lineBiZssOption.series,
            pointBiBcsOption.series,
            ...scatterBuyOption.series,
            ...scatterSellOption.series,
            ...seaMoonOption.series,
            ...mainAreaOption.series
        ],
        legend: {
            data: ["笔", "笔中枢", "线段中枢", "走势", "主力三区"],
            selected: {
                "笔": true, "笔中枢": true, "线段中枢": false, "走势": false, "主力三区": false
            },
            textStyle: {
                color: fcolor
            },
            type: 'scroll',
            width: screenWidth.num < 768 ? '100%' : '50%',
            right: 10,
            top: '5px',
        },
        toolbox: {
            top: '35px',
            feature: {
                ...tagText(),
                ...tagLine(),
                ...tagArrow()
            }
        },
        brush: {
            toolbox: ['rect', 'polygon', 'clear'],
            xAxisIndex: 'all',
            brushLink: 'all',
            brushMode: 'multiple',
            outOfBrush: {
                colorAlpha: 0.1
            }
        },
        tooltip: {
            // show:false,
            trigger: 'item',
            confine: true,
            axisPointer: {
                type: 'cross'
            }
        },
        axisPointer: {
            link: [
                {
                    xAxisIndex: [0]
                },
                {
                    xAxisIndex: [1, 2]
                }
            ],
            label: {
                backgroundColor: '#999',
                padding: 0,
                formatter: (parms) => {
                    const { axisDimension, axisIndex, value } = parms
                    if (axisDimension == 'y') return `{a|${String(value).split('.')[0]}}`;
                    if (axisDimension == 'x') return `{a|${value}}`;
                },
                rich: {
                    a: {
                        padding: [5, 7, 5, 7]
                    }
                }
            }
        },
        xAxis: [
            klinesOption.xAxis,
            seaMoonOption.xAxis,
            macdOption.xAxis
        ],
        yAxis: [
            klinesOption.yAxis,
            seaMoonOption.yAxis,
            macdOption.yAxis
        ],
        title: [
            // {
            //     text: title,
            //     left: 0,
            //     top: '40px',
            //     width: screenWidth.num < 768 ? '100%' : '50%',
            //     textStyle: {
            //         color: fcolor,
            //     }
            // }
        ],
        dataZoom: [
            {
                "show": false,
                "type": "inside",
                "start": dataZoom.start,
                "end": dataZoom.end,
                "xAxisIndex": [0],
                "filterMode": "none",
                "preventDefaultMouseMove": false,
            },
            {
                "show": false,
                "type": "inside",
                "start": 25,
                "end": 75,
                "yAxisIndex": [0],
                "filterMode": "empty",
                "preventDefaultMouseMove": false,
            },
            {
                "show": true,
                "type": "slider",
                "start": dataZoom.start,
                "end": dataZoom.end,
                "orient": "horizontal",
                "xAxisIndex": [
                    0,
                    1,
                    2
                ],
                "zoomLock": false,
                "top": "94%",
                "height": "5%",
                "filterMode": "filter"
            }
        ],
        grid: [{
            show: false,
            zlevel: 0,
            z: 0,
            top: "15%",
            left: "3%",
            right: 60,
            height: "50%",
        },
        {
            show: false,
            zlevel: 0,
            z: 2,
            top: "68%",
            left: "3%",
            right: 60,
            height: "10%",
        },
        {
            show: false,
            zlevel: 0,
            z: 2,
            top: "80%",
            left: "3%",
            right: 60,
            height: "10%",
        }]
    }
    myChart.setOption(option, {
        lazyUpdate: true
    })
    window.addEventListener('resize', (e) => {
        myChart.resize();
        updatePosition(e)
    })
    myChart.on('dataZoom', function (e) {
        updatePosition(e)
    });
    function updatePosition(e) {
        myChart.setOption({
            graphic: tagToolboxs.map(function (item, dataIndex) {
                return {
                    position: myChart.convertToPixel('grid', item.start)
                };
            })
        });
        // 放大缩小
        if (e.type == "datazoom") {
            if (e.batch) dataZoom = e.batch[0]; //储存缩放数据
            else dataZoom = e //储存缩放数据
        } else {
            // 拖动
            dataZoom = e
        }
    }

    // 点击事件
    myChart.on('click', async function (params) {
        // 停止画线点击
        await creatLineText(params)
    });
    // 移动事件
    myChart.on('mousemove', async function (params) { })

    // 图例联动事件
    myChart.on('legendselectchanged', async function (params) {
        let { name, selected } = params
        // 笔中枢联动买点,卖点
        if (name == "笔中枢" && selected["笔中枢"]) {
            selected['笔买点'] = true
            selected['笔卖点'] = true
            myChart.setOption({
                legend: {
                    selected //绑定数据
                }
            })
        } else if (name == "笔中枢" && !selected["笔中枢"]) {
            selected['笔买点'] = false
            selected['笔卖点'] = false
            myChart.setOption({
                legend: {
                    selected //绑定数据
                }
            })
        }
        // 线段联动买点,卖点
        if (name == "线段中枢" && selected["线段中枢"]) {
            selected['线段买点'] = true
            selected['线段卖点'] = true
            myChart.setOption({
                legend: {
                    selected //绑定数据
                }
            })
        } else if (name == "线段中枢" && !selected["线段中枢"]) {
            selected['线段买点'] = false
            selected['线段卖点'] = false
            myChart.setOption({
                legend: {
                    selected //绑定数据
                }
            })
        }
        // 主力三区
        if (name == "主力三区" && selected["主力三区"]) {
            selected['主力三区'] = true
            myChart.setOption({
                legend: {
                    selected //绑定数据
                }
            })
        } else if (name == "主力三区" && !selected["主力三区"]) {
            selected['主力三区'] = false
            myChart.setOption({
                legend: {
                    selected //绑定数据
                }
            })
        }

    })

    // VOL/MACD切换事件 
    myChart.tapSelect = (type) => {
        myChart.clear(); //清空所有属性和数据
        // 处理series
        option.series = [
            ...option.series.filter(i => i.name != 'vol' && i.name != 'MACD'),
            ...macdOption.series.filter(i => i.name == type)
        ];
        myChart.setOption(option, true); //删除后的数据重新绘制
    }
    return myChart
}

// 自定义标注
// 标记文字
function tagText() {
    return {
        mytagText: {
            show: true,
            title: '标记文字',
            icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891',
            onclick: function () {
                ElMessageBox.prompt('请输入要显示的文字', 'Tip', {
                    confirmButtonText: 'OK',
                    cancelButtonText: 'Cancel'
                })
                    .then(({ value }) => {
                        if (!value) return;
                        onClick = true
                        setTypeToolbox = 1
                        tagToolboxs.unshift({
                            text: value,
                            type: 1
                        })
                    })
            }
        },
    }
}
// 标记线段
function tagLine() {
    return {
        mytagLine: {
            show: true,
            title: '标记线段',
            icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891',
            onclick: function () {
                onClick = true
                setTypeToolbox = 2
                myChart.setOption({
                    graphic: []
                });
                tagToolboxs.unshift({
                    text: 'line',
                    type: 2
                })
            }
        },
    }
}
// 标记箭头
function tagArrow() {
    return {
        mytagArrow: {
            show: true,
            title: '标记箭头',
            icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891',
            onclick: function () {
                window.openDrawingBoard()
            }
        },
    }
}
// 画线标字
function creatLineText(params) {
    if (!onClick) return;
    const map = async () => {
        var chartOption = myChart.getOption();
        chartOption.graphic = [];
        await myChart.setOption(chartOption, true);

        let text = tagToolboxs.filter(i => i.type == 1)
        let line = tagToolboxs.filter(i => i.type == 2)

        await myChart.setOption({
            // 画线
            series: line.map((i, v) => {
                return {
                    id: 'line_' + v,
                    type: 'line',
                    smooth: true,
                    data: [i.start, i.end]
                }
            })
        });

        await myChart.setOption({
            graphic: [
                // 文字
                ...text.map(i => {
                    return {
                        type: 'text',
                        position: myChart.convertToPixel('grid', i.start),
                        style: {
                            text: i.text,
                            fill: '#fff'
                        },
                        draggable: true,
                        z: 100,
                    }
                }),
                // 画线
                ...line.map(function (item, dataIndex) {
                    return {
                        type: 'line',
                        position: myChart.convertToPixel('grid', item),
                        draggable: true,
                        z: 100
                    };
                })
            ]
        });
    }

    let { name, value } = params
    // 会是数组 k数据
    if (Array.isArray(value)) value = value[1];
    if (setTypeToolbox == 1) {
        // 标文字
        tagToolboxs[0].start = [name, value]
        map()
    } else if (setTypeToolbox == 2) {
        // 标线段
        if (!tagToolboxs[0].start) {
            tagToolboxs[0].start = [name, value]
            return
        }
        tagToolboxs[0].end = [name, value]
        map()
    }

    onClick = false
    setTypeToolbox = null
}

